#coding:utf-8
#转为Vultr-API设计的批量控制程序
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# @Time: 2018-09-11 2:24
# @Author: Lurker
# @File: vultr.py

import requests
import paramiko
import traceback
import demjson

headers = {'API-Key':''}
# 新开服务器
def create(num):
    # 查看VPSPLANID列表 https://api.vultr.com/v1/plans/list
    # 查看DCID列表 https://api.vultr.com/v1/regions/list
        # "1": "美国 - 纽约"
        # "2": "美国 - 芝加哥"
        # "3": "美国 - 达拉斯"
        # "4": "美国 - 西雅图"
        # "5": "美国 - 洛杉矶"
        # "6": "美国 - 亚特兰大"
        # "7": "荷兰 - 阿姆斯特丹"
        # "8": "英国 - 伦敦"
        # "9": "德国 - 法兰克福"
        # "12": "美国 - 硅谷"
        # "19": "澳大利亚 - 悉尼"
        # "24": "法国 - 巴黎"
        # "25": "日本 - 东京"
        # "39": "美国 - 迈阿密"
        # "40": "新加坡 - 新加坡"
    # 查看OSID列表 https://api.vultr.com/v1/os/list
        # 127 | CentOS 6 x64
        # 147 | CentOS 6 i386
        # 167 | CentOS 7 x64
        # 160 | Ubuntu 14.04 x64
        # 161 | Ubuntu 14.04 i386
        # 215 | Ubuntu 16.04 x64
        # 216 | Ubuntu 16.04 i386
        # 241 | Ubuntu 17.04 x64
        # 242 | Ubuntu 17.04 i386
        # 139 | Debian 7 x64(wheezy)
        # 152 | Debian 7 i386(wheezy)
        # 193 | Debian 8 x64(jessie)
        # 194 | Debian 8 i386(jessie)
        # 244 | Debian 9 x64(stretch)
        # 140 | FreeBSD 10 x64
        # 230 | FreeBSD 11 x64
        # 234 | OpenBSD 6 x64
        # 179 | CoreOS Stable
        # 225 | Fedora 24 x64
        # 233 | Fedora 25 x64
        # 245 | Fedora 26 x64
        # 159 | Custom
        # 164 | Snapshot
        # 180 | Backup
        # 186 | Application
    for i in range(0,num):
        data = {"DCID":40, "OSID":193, "VPSPLANID":203}
        res = requests.post('https://api.vultr.com/v1/server/create', data=data, headers=headers).text
        print(res)

# 重启服务器
def reboot(id):
    data = {"SUBID": id}
    requests.post('https://api.vultr.com/v1/server/reboot', data=data, headers=headers)

# 销毁服务器
def destroy(id):
    data = {"SUBID": id}
    requests.post('https://api.vultr.com/v1/server/destroy', data=data, headers=headers)

# 销毁所有服务器
def destroyall():
    res = requests.get('https://api.vultr.com/v1/server/list', headers=headers).json()
    for i in res:
        data = {"SUBID": i}
        requests.post('https://api.vultr.com/v1/server/destroy', data=data, headers=headers)

# 获取所有服务的IP和密码和服务器ID ID可用于销毁服务器
def getServerInfo():
    res = requests.get('https://api.vultr.com/v1/server/list', headers=headers)
    serversList = demjson.decode(res.text)
    SUBIDS = serversList.keys()
    servers = []
    for SUBID in SUBIDS:
        server = {
            'ip':serversList[SUBID]['main_ip'],
            'password':serversList[SUBID]['default_password'],
            'id':SUBID
        }
        servers.append(server)
    return servers
# 连接测试 id 用于 如果连接失败 销毁
def connect(ip,pwd):
    try:
        ssh = paramiko.SSHClient()
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) # 跳过了远程连接中选择 '是' 的环节
        ssh.connect(ip, 22, 'root', pwd,timeout=10)
        stdin, stdout, stderr = ssh.exec_command('whoami')
        res, err = stdout.read(), stderr.read()
        result = res if res else err
        ssh.close()
        res = result.decode()
        if str(res).find('root')>-1:
            return True
        else:
            return False
    except Exception as e:
        return False

if __name__ == '__main__':
    # create(5)
    # destroyall()
    # exit()
    # exit()
    servers = getServerInfo()
    # print('servers count:',len(servers))
    # if len(servers) < 5:
    #     create(5-len(servers))
    # exit()


    for server in servers:
        if connect(server['ip'],server['password']) == False:
            print(server['ip'],'server can\'t connected! do destroy...')
            print(server)
            destroy(server['id'])
        else:
            print(server['ip'],'connect success......')
            #提交到console
            res = requests.post('http://45.32.100.28:5000/addserver',data={'IP':server['ip'],'PASSWORD':server['password']})
            print(res.text)
    # for i in range(0,len(servers['id'])):
    #     destroy(servers['id'][i])
    # reboot(servers['id'])
